package com.example.controller.admin;


import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.*;
import com.example.service.IOrderDetailService;
import com.example.service.IOrderService;
import com.example.service.IProductHealthItemService;
import com.example.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 管理员-订单Controller控制器
 */
@RestController
@RequestMapping("/admin/order")
public class AdminOrderController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IProductHealthItemService productHealthItemService;

    /**
     * 根据条件分页查询
     * @param pageBean
     * @return
     */
    @RequestMapping("/list")
    public R list(@RequestBody PageBean pageBean){
        System.out.println(pageBean);
        Map<String,Object> map=new HashMap<>();
        map.put("orderNo",pageBean.getQuery().trim());
        map.put("start",pageBean.getStart());
        map.put("pageSize",pageBean.getPageSize());
        List<Order> orderList=orderService.list(map);
        Long total=orderService.getTotal(map);

        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("orderList",orderList);
        resultMap.put("total",total);
        return R.ok(resultMap);
    }


    /**
     * 更新订单状态
     * @param
     * @return
     */
//    @RequestMapping("/updateStatus")
//    public R updateStatus(@RequestBody Order order){
//        Order resultOrder = orderService.getById(order.getId());
//        resultOrder.setStatus(order.getStatus());
//        orderService.updateById(resultOrder);
//        return R.ok();
//    }
    @RequestMapping("/updateStatus")
    @Transactional
    public R updateStatus(@RequestBody Order order) {
        // 获取订单信息
        Order resultOrder = orderService.getById(order.getId());

        // 更新状态
        resultOrder.setStatus(order.getStatus());
        orderService.updateById(resultOrder);

        // 如果是退货/退款，归还库存
        if (order.getStatus() == 3) {
            // 查询订单详情
            List<OrderDetail> orderDetails = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getMId, order.getId()));

            for (OrderDetail orderDetail : orderDetails) {
                if ("normal".equals(orderDetail.getItemType())) {
                    // 普通商品，直接归还库存
                    Product product = productService.getById(orderDetail.getGoodsId());
                    if (product != null) {
                        product.setStock(product.getStock() + orderDetail.getGoodsNumber());
                        productService.updateById(product);
                    }
                } else if ("health".equals(orderDetail.getItemType())) {
                    // 健康商品，归还健康商品组合中的每个商品库存
                    List<ProductHealthItem> healthItems = productHealthItemService.list(new LambdaQueryWrapper<ProductHealthItem>().eq(ProductHealthItem::getHealthId, orderDetail.getGoodsId()));
                    for (ProductHealthItem healthItem : healthItems) {
                        Product product = productService.getById(healthItem.getGoodId());
                        if (product != null) {
                            product.setStock(product.getStock() + orderDetail.getGoodsNumber());
                            productService.updateById(product);
                        }
                    }
                }
            }
        }

        return R.ok();
    }

    /**
     * 删除订单
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id") Integer id){
        orderDetailService.remove(new QueryWrapper<OrderDetail>().eq("mid", id));
        orderService.removeById(id);
        return R.ok();
    }


    //批量删除
    @PostMapping("/deleteBatch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        for (Integer id : ids) {
            orderDetailService.remove(new QueryWrapper<OrderDetail>().eq("mid", id));
            orderService.removeById(id);
        }
        return R.ok();
    }

    //导出数据
    @GetMapping("/export")
    public void exportData(
                           @RequestParam(required = false) String ids,
                           HttpServletResponse response) throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter(true);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        List<Order>orderList;
        if(StrUtil.isNotBlank(ids)){
            List<Integer> idsArr1 = Arrays.stream(ids.split(","))
                    .map(Integer::valueOf).collect(Collectors.toList());
            queryWrapper.in("id", idsArr1);
        }

        orderList = orderService.list(queryWrapper);


//        if(StrUtil.isBlank(orderNo)){
//            Map<String,Object> map=new HashMap<>();
//             orderList=orderService.list(map);
//        }
        writer.write(orderList, true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("订单信息表","UTF-8")+".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();

        writer.flush(outputStream,true);
        outputStream.flush();
        outputStream.close();
    }
}
